package br.com.classificadosonline.servlet;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import br.com.classificadosonline.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CadastroAnuncianteServlet
 */
public class CadastroAnuncianteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Sistema sistema = Sistema.getInstance();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CadastroAnuncianteServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String CEP = request.getParameter("cep");
			String celular = request.getParameter("celular");
			String UF = request.getParameter("uf");
			int numero = Integer.parseInt(request.getParameter("numero"));
			String email = request.getParameter("email");
			String usuario = request.getParameter("usuario");
			String senha = "";
			try {
				senha = Sistema.toPassword(request.getParameter("senha"));
			} catch (NoSuchAlgorithmException e) { }				
			String logradouro = request.getParameter("logradouro");
			String cpf = request.getParameter("cpf");
			String complemento = request.getParameter("complemento");
			String nome = request.getParameter("nome");
			String telefone = request.getParameter("telefone");
			String pais = request.getParameter("pais");
			String bairro = request.getParameter("bairro");
			String Cidade = request.getParameter("cidade");
			boolean SMS;
			if (request.getParameter("sms").equals("true")) SMS = true; else SMS = false;
			sistema.adicionarPessoa(bairro, celular, CEP, Cidade, complemento, cpf, email, logradouro, nome, numero, pais, SMS, telefone, UF, usuario, senha, "ANUNCIANTE");
			request.setAttribute("anunciante", sistema.buscarPessoa(cpf));
			RequestDispatcher dispatcher = request.getRequestDispatcher("/cadastrofinalizado.jsp");
			dispatcher.forward(request, response);
			return;
		}
		catch (Exception e) {
			RequestDispatcher dispatcher = request.getRequestDispatcher("/cadastro.jsp");
			dispatcher.forward(request, response);
			return;
		}
	}

}
